﻿using Microsoft.Extensions.Caching.Memory;
using System.Collections.Concurrent;

namespace 天离安全_天擎.Tl_SerVices
{
    /// <summary>
    /// 数据缓存服务，以下都采用异步多线程来实现获取、设置、清除、暂存
    /// </summary>
    public class GetMemoryCaching_Services
    {
        private readonly IMemoryCache _cache;
        private readonly ConcurrentDictionary<string, string> _cacheKeys;
        /// <summary>
        /// 注册缓存主函数
        /// </summary>
        /// <param name="cache"></param>
        public GetMemoryCaching_Services(IMemoryCache cache)
        {
            _cache = cache;
            _cacheKeys = new ConcurrentDictionary<string, string>();
        }

        /// <summary>
        /// 记录缓存信息
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="absoluteExpiration"></param>
        /// <returns></returns>
        public async Task SetCacheAsync(string key, string value, TimeSpan? absoluteExpiration = null)
        {
            await Task.Run(() =>
            {
                var cacheEntryOptions = new MemoryCacheEntryOptions
                {
                    AbsoluteExpirationRelativeToNow = absoluteExpiration ?? TimeSpan.FromMinutes(30)
                };
                _cache.Set(key, value, cacheEntryOptions);

                // 记录缓存键
                _cacheKeys[key] = value;
            });
        }

        /// <summary>
        /// 获取缓存信息
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public async Task<string> GetCacheAsync(string key)
        {
            return await Task.Run(() =>
            {
                _cache.TryGetValue(key, out string? cachedValue);
                return cachedValue;
            });
        }

        /// <summary>
        /// 清空单个缓存
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public async Task ClearCacheAsync(string key)
        {
            await Task.Run(() =>
            {
                _cache.Remove(key);
                _cacheKeys.TryRemove(key, out _); // 从记录中移除键
            });
        }

        /// <summary>
        /// 清空所有缓存
        /// </summary>
        /// <returns></returns>
        public async Task ClearAllCacheAsync()
        {
            await Task.Run(() =>
            {
                foreach (var key in _cacheKeys.Keys)
                {
                    _cache.Remove(key);
                }
                _cacheKeys.Clear(); // 清空记录的键
            });
        }
    }
}
